import { toScientificValue } from "@app-nextmesh-env/nextmesh/utils"
import styled from "styled-components"

const MeasureScale = styled.div`
	width: 200px;
	height: 4px;
	border-left: 2px solid #444;
	border-right: 2px solid #444;
	border-bottom: 2px solid #444;
`
// 刻度基准
const INIT_SCALE = 0.1
const SCALE_UNIT = 48 // 一个刻度的宽度
const scaleStandards = [2, 2.5, 2] // 1, 2, 5，循环取值
const MIN_MEASURE_WIDTH = 90
const MAX_MEASURE_WIDTH = 200
export function ScaleBar({ zoom }: { zoom?: number }) {
	if (zoom === undefined) {
		return null
	}
	let width = zoom * SCALE_UNIT
	const scaleStandardsLength = scaleStandards.length
	let i = 1000000 * scaleStandardsLength // 取一个比较大的中间值，且是scaleStandards长度的倍数
	let scaleRate = 1
	if (width < MIN_MEASURE_WIDTH) { // 小于最小值，需要放大
		while (width < MIN_MEASURE_WIDTH) {
			i-- // 从最后一个开始
			const std = scaleStandards[i % scaleStandardsLength]
			width *= std
			scaleRate *= std
		}
	} else if (width > MAX_MEASURE_WIDTH) { // 大于最大值，需要缩小
		while (width > MAX_MEASURE_WIDTH) {
			// i = i // 从第一个开始
			const std = scaleStandards[i % scaleStandardsLength]
			width /= std
			scaleRate /= std
			i++
		}
	}
	const scale = toScientificValue(INIT_SCALE * scaleRate, 10)
	return (
		<div>
			<MeasureScale style={{ width: `${width}px` }} />
			<div style={{ textAlign: 'center', marginTop: '4px', fontSize: '12px' }}>
				<span>{scale}</span>
				<span>mm</span>
			</div>
		</div>
	)
}
